import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '../utils/request'

export const useProfileStore = defineStore('profile', () => {
  const profile = ref(null)
  const userArticles = ref([])
  const userComments = ref([])
  const likedArticles = ref([])
  const isLoading = ref(false)
  const error = ref(null)

  // 获取用户资料
  const fetchUserProfile = async (userId) => {
    isLoading.value = true
    error.value = null
    
    try {
      const data = await request.get(`/profile/${userId}`)
      const extendedData = await request.get(`/profile/${userId}/extended`)
      console.log(extendedData.github);
      
      profile.value = {
        ...data,
        achievements: extendedData.achievements,
        github: extendedData.github,
        twitter: extendedData.twitter,
        website: extendedData.website
      }
      return data
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户文章列表
  const fetchUserArticles = async (userId) => {
    try {
      const data = await request.get(`/profile/${userId}/articles`)
      console.log(data)
      userArticles.value = data
      return data
    } catch (err) {
      console.error('获取用户文章失败:', err)
      throw err
    }
  }

  // 获取用户评论列表
  const fetchUserComments = async (userId) => {
    try {
      const data = await request.get(`/profile/${userId}/comments`)
      console.log(data)
      userComments.value = data
      return data
    } catch (err) {
      console.error('获取用户评论失败:', err)
      throw err
    }
  }

  // 获取用户点赞的文章
  const fetchLikedArticles = async (userId) => {
    try {
      const data = await request.get(`/profile/${userId}/likes`)
      console.log(data)
      likedArticles.value = data
      return data
    } catch (err) {
      console.error('获取点赞文章失败:', err)
      throw err
    }
  }

  // 更新用户扩展信息
  const updateUserExtendedInfo = async (userId, data) => {
    try {
      await request.put(`/profile/${userId}/extended`, data)
      if (profile.value) {
        profile.value = {
          ...profile.value,
          achievements: data.achievements,
          github: data.github,
          twitter: data.twitter,
          website: data.website
        }
      }
      return { message: '更新成功' }
    } catch (err) {
      console.error('更新用户扩展信息失败:', err)
      throw err
    }
  }

  // 更新用户资料
  const updateProfile = async (userId, profileData) => {
    try {
      const data = await request.put(`/profile/${userId}`, profileData)
      profile.value = {
        ...profile.value,
        ...profileData
      }
      return data
    } catch (err) {
      console.error('更新资料失败:', err)
      throw err
    }
  }

  return {
    profile,
    userArticles,
    userComments,
    likedArticles,
    isLoading,
    error,
    fetchUserProfile,
    fetchUserArticles,
    fetchUserComments,
    fetchLikedArticles,
    updateUserExtendedInfo,
    updateProfile
  }
}) 